package com.vrv.netmgr.database.downservice;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.util.Log;

import com.vrv.common.GlobalConstants;
import com.vrv.common.UrlPrefix;
import com.vrv.common.config.EdpModule;
import com.vrv.common.util.DateUtils;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.netmgr.database.TypeConfig;
import com.vrv.netmgr.database.dao.AlarmStatisticsDao;
import com.vrv.netmgr.database.dao.UpdateLogDao;
import com.vrv.netmgr.database.table.AlarmStatistics;
import com.vrv.netmgr.database.table.UpdateLog;

public class AlarmStatisticsDown {
	private static final String TAG = AlarmStatisticsDown.class.getSimpleName();
	private static final boolean DEBUG = true && GlobalConstants.DEBUG;
	
	public static void startCache() {
		if (DEBUG) Log.e(TAG, "startCache()");
		
		String reponse = down();
		AlarmStatistics alarm = analyse(reponse);
		if (null == alarm) {
			return;
		}
		save(alarm);
	}

	
	public static String down() {
		if (DEBUG) Log.e(TAG, "down()");
		
    	String prefix = UrlPrefix.getUrlPrefix2();
    	String url = prefix + "/" + EdpModule.AlarmStatistics.WARNINGINFO_STATISTICS;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String response = httpClientToServer.doPost(url, null);
		
		return response;
	}

	public static AlarmStatistics analyse(String response) {
		if (DEBUG) Log.e(TAG, "analyse()");
		
		if (HttpClientToServer.DO_POST_ERR.equals(response) || HttpClientToServer.DO_POST_EXCEPT.equals(response)) {
			return null;
		}
		
		AlarmStatistics alarm = new AlarmStatistics();
		
		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			
			boolean bRet = jsonObj.getBoolean("success");
			if (!bRet) {
				return null;
			}
			
			JSONObject jObj = jsonObj.getJSONObject("record");
			
			alarm.setFfwl(jObj.getLong("ffwl"));
			alarm.setSbbh(jObj.getLong("sbbh"));
			alarm.setIpbh(jObj.getLong("ipbh"));
			alarm.setTtxz(jObj.getLong("ttxz"));
			alarm.setLlyc(jObj.getLong("llyc"));
			alarm.setZdbj(jObj.getLong("zdbj"));
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return alarm;
	}

	public static boolean save(AlarmStatistics alarm) {
		if (DEBUG) Log.e(TAG, "save()");
		
		AlarmStatisticsDao.insert(alarm);
		
		UpdateLog uLog = new UpdateLog();
		uLog.setMode(TypeConfig.ALARM_STATISTICS);
		uLog.setTime(DateUtils.getCurrentTime());
		UpdateLogDao.insert(uLog);
		
		return true;
	}
}
